package com.xiaohudie.JUC;

/**
 * @Author xiao hu die
 * @Date 2022/1/15 15:16
 * @Version 1.0
 */

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**红绿灯的实现Semaphore*/
public class Thread10 {
    public static void main(String[] args) {
        Semaphore semaphore =new Semaphore(2);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                   /**抢占车位*/
                   semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢占到了车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName()+"离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    /**释放车位情况*/
                    semaphore.release();
                }

            },String.valueOf(i)).start();
        }
    }
}
